<template>
  <a-modal v-model:visible="config.visible" :title="config.title" :size="appStore.table.size" @cancel="handleCancel"
    @before-ok="handleBeforeOk">
    <a-form ref="formRef" :model="form" :rules="rules">
      <a-form-item label="名称" field="name">
        <a-input v-model="form.name" />
      </a-form-item>

      <a-form-item label="描述" field="description">
        <a-input v-model="form.description" />
      </a-form-item>

      <a-form-item label="资源类型" field="types">
        <!-- <a-input v-model="form.types" /> -->
        <a-select v-model="form.types" placeholder="请选择资源类型">
          <a-option v-for="resourceType in resourceTypes" :key="resourceType.id" :value="resourceType.id"
            :label="resourceType.name" />
        </a-select>
      </a-form-item>
      <!-- <a-form-item label="公告封面" field="cover">
        <image-upload v-model="form.cover" />
      </a-form-item> -->

      <!-- 需要处理这个文件上传------------- -->
      <a-form-item label="文件" field="file">
        <!-- <input
          id=""
          ref="customerNode"
          hidden
          type="file"
          name=""
          placeholder="file"
          @change="customeChangeFun"
        />
        <a-button type="primary" @click="selectFile"> 请选择文件 </a-button>
        <span>{{ fileName }}</span>
        <span></span> -->
        <a-upload v-model:file-list="form.fileList" name="image" :auto-upload="false" :multiple="false" :headers="headers"
          @custom-request="customRequestFun" @change="handleChange">
          <a-button>
            <upload-outlined></upload-outlined>
            点击上传
          </a-button>
        </a-upload>
      </a-form-item>

      <!-- <a-form-item label="排序" field="sort">
        <a-input v-model="form.sort" />
      </a-form-item> -->
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
// import type { UploadChangeParam } from 'ant-design-vue';

const emit = defineEmits(['ok']);
const appStore = useAppStore();
const formRef = ref();
const config = reactive({
  visible: false,
  isCreate: false,
  title: '',
});

const customerNode = ref();

const form = ref({
  id: undefined,
  name: undefined,
  description: undefined,
  cover: undefined,
  types: undefined,
  file: undefined,
  sort: undefined,
  fileList: [],
});

const resetForm = () => {
  form.value = {
    id: undefined,
    name: undefined,
    description: undefined,
    cover: undefined,
    types: undefined,
    file: undefined,
    sort: undefined,
    fileList: [],
  };
};

const rules = {
  word: [{ required: true, message: '请输入违禁词' }],
};

const show = () => {
  formRef.value.resetFields();
  resetForm();
  config.isCreate = true;
  config.title = '新增';
  config.visible = true;
};

const resourceTypes = ref([{ id: undefined, name: undefined }]);

const getResourceTypes = async () => {
  try {
    resourceTypes.value = await axios.get(
      `/api/admin/resources-types/all/list`
    );
  } catch (e: any) {
    useHandleError(e);
  }
};

const fileList = ref([]);
const headers = {
  authorization: 'authorization-text',
};
const selectFile = () => {
  customerNode.value?.click();
};
const customeChangeFun = (e: any) => {
  form.value.file = e.target.files[0] as any;
  customerNode.value = '';
};

const handleChange = (info) => {
  console.log(info[0]);
  try {
    form.value.file = info[0].file;
  } catch (error) {
    console.log(error);
  }
  console.log(form.value.file);
  // if (info.file.status !== 'uploading') {
  //   console.log(info.file, info.fileList);
  // }
  // if (info.file.status === 'done') {
  //   // message.success(`${info.file.name} file uploaded successfully`);
  // } else if (info.file.status === 'error') {
  //   // message.error(`${info.file.name} file upload failed.`);
  // }
};
const customRequestFun = () => { };

// const action = computed(() => {
//   const baseURL = import.meta.env.VITE_API_BASE_URL || '';
//   return `${baseURL}/api/admin/resources/upload`;
// });

getResourceTypes();

const showEdit = async (id: any) => {
  formRef.value.resetFields();
  resetForm();
  config.isCreate = false;
  config.title = '编辑';

  try {
    form.value = await axios.get(`/api/admin/resources/${id}`);
  } catch (e: any) {
    useHandleError(e);
  }

  config.visible = true;
};

const deleteAt = async (id: any) => {
  try {
    const data = { id };
    await axios.postForm<any>(
      `/api/admin/resources/delete`,
      jsonToFormData(data)
    );
    useNotificationSuccess('操作成功');
    emit('ok');
  } catch (e: any) {
    useHandleError(e);
  }
};

const handleCancel = () => {
  formRef.value.resetFields();
};
const handleBeforeOk = async (done: (closed: boolean) => void) => {
  const validateErr = await formRef.value.validate();
  if (validateErr) {
    done(false);
    return;
  }
  try {
    const url = config.isCreate
      ? '/api/admin/resources/upload'
      : '/api/admin/resources/update';
    await axios.postForm<any>(url, jsonToFormData(form.value));
    useNotificationSuccess('操作成功');
    emit('ok');
    done(true);
  } catch (e: any) {
    useHandleError(e);
    done(false);
  }
};

defineExpose({
  show,
  showEdit,
  deleteAt,
});
</script>

<style lang="less" scoped></style>
